import { defineStore } from 'pinia'
import axios from "axios";

export const userStore = defineStore('user',{
    //存储全局变量
    state:()=>({
        user:{},         //  用户信息
        loggedIn:false,  //  是否登录
        permissions: [], // 添加权限字段
    }),
    //同步修改状态信息
    actions:{
        fetchPermissions(userId) {
            axios.get(`/permissions/getPermissionsByUserId/${userId}`).then(res => {
                this.permissions = res.data.obj

                // 持久化权限数据
                localStorage.setItem('userPermissions', JSON.stringify(this.permissions));

            })
        },
        setUser(user){
            this.user = user;
        },
        setStatus(status){
            this.loggedIn = status;
        },
        initStore() {
            this.user = JSON.parse(sessionStorage.getItem("user")) || {};
            this.loggedIn = sessionStorage.getItem("loggedIn") ? true : false;

            const storedPermissions = localStorage.getItem('userPermissions');
            if (storedPermissions) {
                this.permissions = JSON.parse(storedPermissions);
            }
        }
    },
    persist: {
        enable: true,
        storage: sessionStorage
    }

})
